import threading

import mysql.connector

db_config = {
    'host': 'localhost',
    'user': 'root',
    'port': 3306,
    'password': 'krokozyabra',
    'database': 'bookschema'
}


# Singleton pattern for database connection
class Database:
    _instance = None
    _lock = threading.Lock()

    def __new__(cls):
        if cls._instance is None:
            with cls._lock:
                if cls._instance is None:
                    cls._instance = super().__new__(cls)
                    cls._instance.connection = mysql.connector.connect(**db_config)
                    cls._instance.cursor = cls._instance.connection.cursor()
        return cls._instance




    def execute_query(self, query, params=None):

        connection = mysql.connector.connect(**db_config)
        cursor = connection.cursor()

        if params is None:
            cursor.execute(query)
        else:
            cursor.execute(query, params)
        result = cursor.fetchall()
        connection.commit()

        cursor.close()
        connection.close()
        return result

    def close_connection(self):
        self.cursor.close()
        self.connection.close()
